/**
The MIT License (MIT)

Copyright (c) 2017 simpleplus

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.oschina.simpleplus.ellieproducer;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import net.oschina.simpleplus.ellieapi.Request;
import net.oschina.simpleplus.ellieapi.Response;
import net.oschina.simpleplus.ellieapi.net.ProtoStuffDecoder;
import net.oschina.simpleplus.ellieapi.net.ProtoStuffEncoder;

public class NettyProducer extends SimpleChannelInboundHandler<Response> implements Producer {
	
	
	private static final Logger log = LoggerFactory.getLogger(NettyProducer.class);

	private static final long parallelismThreshold = Runtime.getRuntime().availableProcessors() * 2;
	
	private Channel channel;
	
	private static ConcurrentHashMap<String, ProducerCallBack> pcbCaches = new ConcurrentHashMap<>();
	
	protected NioEventLoopGroup group = new NioEventLoopGroup();
	
	public NettyProducer(String addr) throws InterruptedException{
		String[] addrs = addr.split(":");
		channel = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(
				new ChannelInitializer<Channel>() {

					@Override
					protected void initChannel(Channel ch) throws Exception {
						ch.pipeline().addLast(
								new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4),
								new ProtoStuffDecoder(Response.class),
								new ProtoStuffEncoder(),
								NettyProducer.this);
					}
				}
				).connect(addrs[0], Integer.parseInt(addrs[1])).sync().channel();
	}

	@Override
	public void send(Request request, ProducerCallBack pcb) {
		//log.info("send req {}", request);
		pcbCaches.putIfAbsent(request.getMessageId(), pcb);
		channel.writeAndFlush(request);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Response msg) throws Exception {
		//log.info("channelRead0 resp {}", msg);
		ProducerCallBack producerCallBack = pcbCaches.get(msg.getMessageId());
		if(producerCallBack != null){
			producerCallBack.setResult(msg);	
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//log.info("channelActive");
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		//log.info("channelInactive");
		if(!pcbCaches.isEmpty()){
			synchronized (pcbCaches) {
				if(!pcbCaches.isEmpty()){
					pcbCaches.forEachValue(parallelismThreshold, (pcb ->{
						pcb.onClose();
					}));
					pcbCaches.clear();
				}
				
			}
			
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		log.error("exceptionCaught", cause);
	}

	@Override
	public void shutdown() {
		group.shutdownGracefully();
		//pcbCaches.clear();
		//log.info("shutdown..");
	}
	
	public boolean validate(){
		return channel != null && channel.isActive();
	}

}
